<template>
  <div class="page-container">
    <header class="header">
      <div class="header-content">
        <router-link to="/" class="logo">
          <h1>匿名社交网络系统</h1>
        </router-link>
        <div class="user-info">
          <el-dropdown @command="handleCommand">
            <div class="user-dropdown">
              <el-avatar :size="32" :src="userStore.userInfo?.avatar">
                {{ userStore.userInfo?.nickname?.[0] || userStore.userInfo?.username?.[0] }}
              </el-avatar>
              <span class="username">{{ userStore.userInfo?.nickname || userStore.userInfo?.username }}</span>
              <el-icon><arrow-down /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-if="userStore.userInfo?.role === 'USER'" command="profile">
                  <el-icon><user /></el-icon>个人资料
                </el-dropdown-item>
                <el-dropdown-item v-if="userStore.userInfo?.role === 'USER'" command="friends">
                  <el-icon><user-filled /></el-icon>关注列表
                </el-dropdown-item>
                <el-dropdown-item v-if="userStore.userInfo?.role === 'ADMIN'" command="dashboard">
                  <el-icon><Odometer /></el-icon>仪表盘
                </el-dropdown-item>
                <el-dropdown-item v-if="userStore.userInfo?.role === 'ADMIN'" command="k-anonymity">
                  <el-icon><Setting /></el-icon>K匿名配置
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><switch-button /></el-icon>退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </header>

    <main class="main-content">
      <div class="content-wrapper">
        <!-- 发布动态 -->
        <div class="post-form">
          <el-card>
            <el-form @submit.prevent="handleCreatePost">
              <el-form-item>
                <el-input
                  v-model="newPost.content"
                  type="textarea"
                  :rows="3"
                  placeholder="分享新动态..."
                  resize="none"
                />
              </el-form-item>
              <div class="post-form-footer">
                <el-upload
                  class="upload-images"
                  action="/api/upload"
                  :show-file-list="false"
                  :on-success="handleUploadSuccess"
                  multiple
                  :limit="9"
                  accept="image/*"
                  :headers="uploadHeaders"
                >
                  <el-button :icon="Picture">上传图片</el-button>
                </el-upload>
                <el-button type="primary" :loading="posting" @click="handleCreatePost">
                  发布
                </el-button>
              </div>
              <!-- 图片预览 -->
              <div v-if="newPost.images.length" class="image-preview">
                <div
                  v-for="(image, index) in newPost.images"
                  :key="index"
                  class="image-item"
                >
                  <el-image
                    :src="image"
                    fit="cover"
                    @click="previewImage(image)"
                  />
                  <el-icon class="delete-icon" @click="removeImage(index)">
                    <close />
                  </el-icon>
                </div>
              </div>
            </el-form>
          </el-card>
        </div>

        <!-- 动态列表 -->
        <div class="posts-list">
          <el-empty
            v-if="!posts.length"
            description="暂无动态"
          />
          <el-card v-for="post in posts" :key="post.id" class="post-card">
            <div class="post-header">
              <div class="post-author">
                <el-avatar 
                  :size="48" 
                  :src="post.user.avatar" 
                  @click="showUserInfo(post.user)"
                >
                  {{ post.user.nickname?.[0] || post.user.username?.[0] }}
                </el-avatar>
                <div class="author-info">
                  <span class="author-name" @click="showUserInfo(post.user)">{{ post.user.nickname || post.user.username }}</span>
                  <span class="post-time">{{ formatTime(post.createTime) }}</span>
                </div>
              </div>
            </div>
            <p class="post-content">{{ post.content }}</p>
            <div v-if="post.images?.length" class="post-images">
              <el-image
                v-for="(image, index) in post.images"
                :key="index"
                :src="image"
                :preview-src-list="post.images"
                fit="cover"
                class="post-image"
                @click="previewImage(image, post.images)"
              />
            </div>
            <div class="post-actions">
              <el-button
                :type="post.liked ? 'primary' : ''"
                :icon="Star"
                @click="handleLike(post)"
              >
                {{ post.likeCount || '点赞' }}
              </el-button>
              <el-button :icon="ChatDotRound" @click="showComments(post)">
                {{ post.commentCount || '评论' }}
              </el-button>
            </div>
          </el-card>

          <!-- 加载更多 -->
          <div v-if="posts.length === 10" class="load-more">
            <el-button
              :loading="loading"
              @click="loadMore"
            >
              加载更多
            </el-button>
          </div>
        </div>
      </div>
    </main>

    <!-- 评论对话框 -->
    <el-dialog
      v-model="commentDialog.visible"
      title="评论"
      width="500px"
    >
      <div class="comment-list">
        <div v-if="!commentDialog.comments.length" class="empty-tip">
          暂无评论
        </div>
        <div
          v-for="comment in commentDialog.comments"
          :key="comment.id"
          class="comment-item"
        >
          <div class="comment-user">
            <el-avatar :size="32" :src="comment.user.avatar">
              {{ comment.user.nickname?.[0] || comment.user.username?.[0] }}
            </el-avatar>
            <div class="comment-info">
              <p class="comment-content">{{ comment.content }}</p>
            </div>
            <el-button
              v-if="comment.user.id === userStore.userInfo.id"
              type="danger"
              :icon="Delete"
              circle
              size="small"
              class="delete-comment"
              @click="handleDeleteComment(comment)"
            />
          </div>
          <span class="comment-username">{{ comment.user.nickname || comment.user.username }}</span>
          <span class="comment-time" style="margin-left: 10px;">{{ formatTime(comment.createTime) }}</span>
        </div>
      </div>
      <template #footer>
        <div class="comment-form">
          <el-input
            v-model="commentDialog.content"
            placeholder="写下你的评论..."
            @keyup.enter="handleComment"
          />
          <el-button type="primary" @click="handleComment">
            发送
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户信息对话框 -->
    <el-dialog
      v-model="userInfoDialog.visible"
      title="用户信息"
      width="400px"
      class="user-info-dialog"
    >
      <div class="user-info-content">
        <div class="user-avatar">
          <el-avatar :size="80" :src="userInfoDialog.user?.avatar">
            {{ userInfoDialog.user?.nickname?.[0] || userInfoDialog.user?.username?.[0] }}
          </el-avatar>
        </div>
        <div class="user-details">
          <h3>{{ userInfoDialog.user?.nickname}}@{{ userInfoDialog.user?.username }}</h3>
          <div class="friend-action" v-if="userInfoDialog.user?.id !== userStore.userInfo.id">
            <el-button
              type="primary"
              :loading="userInfoDialog.loading"
              @click="handleAddFriend"
              v-if="!userInfoDialog.isFriend"
            >
              添加关注
            </el-button>
            <el-button
              type="danger"
              :loading="userInfoDialog.loading"
              @click="handleDeleteFriend"
              v-else
            >
              取消关注
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowDown,
  User,
  UserFilled,
  SwitchButton,
  Picture,
  Close,
  ChatDotRound,
  Star,
  Delete,
  Odometer,
  Setting
} from '@element-plus/icons-vue'
import { createPost, getPosts, likePost, commentPost, getComments, deleteComment, getFriendList, addFriend, deleteFriend } from '../api'

const router = useRouter()
const userStore = useUserStore()

const posts = ref([])
const newPost = ref({
  content: '',
  images: []
})
const posting = ref(false)
const loading = ref(false)
const page = ref(1)
const commentDialog = ref({
  visible: false,
  postId: null,
  content: '',
  comments: []
})
const userInfoDialog = ref({
  visible: false,
  user: null,
  loading: false,
  isFriend: false
})

const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'friends':
      router.push('/friends')
      break
    case 'dashboard':
      router.push('/admin/dashboard')
      break
    case 'k-anonymity':
      router.push('/admin/k-anonymity')
      break
    case 'logout':
      userStore.logout()
      router.push('/login')
      break
  }
}

const handleCreatePost = async () => {
  if (!newPost.value.content.trim() && !newPost.value.images.length) {
    ElMessage.warning('请输入动态内容或上传图片')
    return
  }

  try {
    posting.value = true
    await createPost(newPost.value)
    ElMessage.success('发布成功')
    newPost.value = { content: '', images: [] }
    page.value = 1
    await fetchPosts()
  } catch (error) {
    ElMessage.error('发布失败')
  } finally {
    posting.value = false
  }
}

const uploadHeaders = {
  Authorization: `Bearer ${localStorage.getItem('token')}`
}

const handleUploadSuccess = (response) => {
  if (response.code === 200) {
    newPost.value.images.push(response.data.url)
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

const removeImage = (index) => {
  newPost.value.images.splice(index, 1)
}

const previewImage = (image, imageList) => {
  // Element Plus的el-image组件已经处理了预览功能
}

const handleLike = async (post) => {
  try {
    await likePost(post.id)
    post.liked = !post.liked
    post.likeCount += post.liked ? 1 : -1
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const showComments = async (post) => {
  commentDialog.value = {
    visible: true,
    postId: post.id,
    content: '',
    comments: []
  }
  await fetchComments()
}

const fetchComments = async () => {
  try {
    const response = await getComments(commentDialog.value.postId)
    commentDialog.value.comments = response.data
  } catch (error) {
    ElMessage.error('获取评论失败')
  }
}

const handleComment = async () => {
  if (!commentDialog.value.content.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }

  try {
    await commentPost(commentDialog.value.postId, commentDialog.value.content)
    ElMessage.success('评论成功')
    commentDialog.value.content = ''
    await fetchComments()
    await fetchPosts()
  } catch (error) {
    ElMessage.error('评论失败')
  }
}

const formatTime = (time) => {
  const date = new Date(time)
  const now = new Date()
  const diff = now - date

  // 小于1分钟
  if (diff < 60000) {
    return '刚刚'
  }
  // 小于1小时
  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  }
  // 小于24小时
  if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  }
  // 小于30天
  if (diff < 2592000000) {
    return `${Math.floor(diff / 86400000)}天前`
  }
  // 其他
  return date.toLocaleDateString()
}

const loadMore = async () => {
  if (loading.value) return
  page.value++
  await fetchPosts()
}

const fetchPosts = async () => {
  try {
    loading.value = true
    const response = await getPosts({ page: page.value, size: 10 })
    if (page.value === 1) {
      posts.value = response.data.records
    } else {
      posts.value.push(...response.data.records)
    }
  } catch (error) {
    ElMessage.error('获取动态失败')
  } finally {
    loading.value = false
  }
}

const handleDeleteComment = async (comment) => {
  try {
    await ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteComment(comment.id)
    ElMessage.success('删除成功')
    await fetchComments()
    await fetchPosts()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const showUserInfo = async (user) => {
  userInfoDialog.value.visible = true
  userInfoDialog.value.user = user
  userInfoDialog.value.loading = true
  try {
    // 检查是否已经是关注
    const response = await getFriendList()
    userInfoDialog.value.isFriend = response.data.friends.some(friend => friend.id === user.id)
  } catch (error) {
    ElMessage.error('获取关注列表失败')
  } finally {
    userInfoDialog.value.loading = false
  }
}

const handleAddFriend = async () => {
  try {
    userInfoDialog.value.loading = true
    await addFriend(userInfoDialog.value.user.id)
    ElMessage.success('添加关注成功')
    userInfoDialog.value.isFriend = true
  } catch (error) {
    ElMessage.error('添加关注失败')
  } finally {
    userInfoDialog.value.loading = false
  }
}

const handleDeleteFriend = async () => {
  try {
    await ElMessageBox.confirm('确定要删除这个关注吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    userInfoDialog.value.loading = true
    await deleteFriend(userInfoDialog.value.user.id)
    ElMessage.success('取消关注成功')
    userInfoDialog.value.isFriend = false
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消关注失败')
    }
  } finally {
    userInfoDialog.value.loading = false
  }
}

onMounted(() => {
  fetchPosts()
})
</script>

<style scoped>
.main-content {
  padding-top: 80px;
}

.content-wrapper {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.logo {
  text-decoration: none;
}

.logo h1 {
  margin: 0;
  font-size: 24px;
  color: var(--primary-color);
}

.user-info {
  display: flex;
  align-items: center;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-dropdown:hover {
  background-color: var(--background-color);
}

.username {
  margin: 0 8px;
  color: var(--text-color);
}

.post-form {
  margin-bottom: 20px;
}

.post-form-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.image-preview {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
  gap: 8px;
  margin-top: 10px;
}

.image-item {
  position: relative;
  aspect-ratio: 1;
}

.image-item .el-image {
  width: 100%;
  height: 100%;
  border-radius: 4px;
}

.delete-icon {
  position: absolute;
  top: 5px;
  right: 5px;
  padding: 4px;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  cursor: pointer;
  transition: background-color 0.3s;
}

.delete-icon:hover {
  background-color: rgba(0, 0, 0, 0.7);
}

.post-card {
  margin-bottom: 20px;
}

.post-header {
  margin-bottom: 15px;
}

.post-author {
  display: flex;
  align-items: center;
}

.author-info {
  margin-left: 10px;
  display: flex;
  flex-direction: column;
}

.author-name {
  font-weight: 500;
  color: var(--text-color);
}

.post-time {
  font-size: 12px;
  color: var(--text-color-secondary);
}

.post-content {
  margin: 15px 0;
  white-space: pre-wrap;
  word-break: break-all;
}

.post-images {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
  margin-bottom: 15px;
}

.post-image {
  aspect-ratio: 1;
  border-radius: 4px;
  overflow: hidden;
}

.post-actions {
  display: flex;
  gap: 15px;
  padding-top: 10px;
  border-top: 1px solid var(--border-color);
}

.load-more {
  text-align: center;
  margin: 20px 0;
}

.comment-form {
  display: flex;
  gap: 10px;
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 5px;
}

:deep(.el-card__body) {
  padding: 20px;
}

@media screen and (max-width: 768px) {
  .content-wrapper {
    padding: 0 10px;
  }

  .post-images {
    grid-template-columns: repeat(2, 1fr);
  }
}

.comment-list {
  max-height: 400px;
  overflow-y: auto;
  padding: 0 20px;
}

.empty-tip {
  text-align: center;
  color: var(--text-color-secondary);
  padding: 20px 0;
}

.comment-item {
  padding: 15px 0;
  border-bottom: 1px solid var(--border-color);
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-user {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  justify-content: space-between;
}

.comment-info {
  margin-left: 10px;
  display: flex;
  flex-direction: column;
}

.comment-username {
  font-weight: 500;
  color: var(--text-color);
}

.comment-time {
  font-size: 12px;
  color: var(--text-color-secondary);
}

.comment-content {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-all;
  color: var(--text-color);
}

.comment-form {
  display: flex;
  gap: 10px;
  padding: 0 20px;
}

.delete-comment {
  opacity: 0;
  transition: opacity 0.3s;
}

.comment-item:hover .delete-comment {
  opacity: 1;
}

.user-info-dialog {
  .user-info-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
  }

  .user-avatar {
    margin-bottom: 20px;
  }

  .user-details {
    text-align: center;

    h3 {
      margin: 0 0 20px;
      color: var(--text-color);
    }
  }

  .friend-action {
    margin-top: 20px;
  }
}

.user-info-dialog :deep(.user-info-content) {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.user-info-dialog :deep(.user-avatar) {
  margin-bottom: 20px;
}

.user-info-dialog :deep(.user-details) {
  text-align: center;
}

.user-info-dialog :deep(.user-details h3) {
  margin: 0 0 20px;
  color: var(--text-color);
}

.user-info-dialog :deep(.friend-action) {
  margin-top: 20px;
}
</style> 